package javabasic.slipch.prime;
import java.util.Iterator;
import java.util.ArrayList;
import java.util.List;

final public class PrimeNumbersList implements Iterable<Integer> {

	public PrimeNumbersList(int upperBoundaryValue) {
		build( upperBoundaryValue );
		return;
	}
	
	@Override
    public final Iterator<Integer> iterator() {
		return list.iterator();
	}
	
	private void build( int upperBoundaryValue ) {
		if (upperBoundaryValue < 2) {
			return;
		}
		list.add(2);
		for (int newValue = 3; newValue <= upperBoundaryValue; ++newValue) {
			tryAddNextValue( newValue );
		};
		return;
	}
	
	private boolean checkValue(int value) {
		for (int prime: list) {
				if (value % prime == 0) {
					return false;
				}
		}
		return true;
	}
	
	private void tryAddNextValue(int value) {
	
		if (value < list.get(list.size()-1)) {
			throw new IllegalArgumentException();
		}
		
		if (checkValue( value )) {
			list.add(value);
		}
		
	}
	
	private List<Integer> list = new ArrayList<Integer>();
}